package com.jacky.dubbo3.standalone;

import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Properties;

/**
 * 第一种启动一个内嵌的单例zk服务的方式
 */
public class ZkEmbeddedServerOne {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZkEmbeddedServerOne.class);

    Properties props;

    /**
     * @param tickTime   zk中最小时间单元的长度
     * @param dataDir    zk服务器存储快照文件的目录
     * @param clientPort 对外服务端口
     * @param initLimit  leader服务器等待follower启动,并完成数据同步的时间
     * @param syncLimit  leader服务器和follower之间进行心跳检测的最大延时时间
     */
    public ZkEmbeddedServerOne(String tickTime, String dataDir, String clientPort, String initLimit, String syncLimit) {
        props = new Properties();
        props.put("tickTime", tickTime);
        props.put("dataDir", dataDir);
        props.put("clientPort", clientPort);
        props.put("initLimit", initLimit);
        props.put("syncLimit", syncLimit);
    }

    public void start() {
        QuorumPeerConfig qpConfig = new QuorumPeerConfig();
        try {
            qpConfig.parseProperties(props);
            ZooKeeperServerMain zkServer = new ZooKeeperServerMain();
            ServerConfig config = new ServerConfig();
            config.readFrom(qpConfig);
            zkServer.runFromConfig(config);
        } catch (Exception e) {
            LOGGER.error("启动zk内嵌服务异常:", e);
        }
    }

    public static void main(String[] args) {
        ZkEmbeddedServerOne zookeeper = new ZkEmbeddedServerOne("2000", new File(System.getProperty("java.io.tmpdir"), "zookeeper").getAbsolutePath(),
                "2181", "10", "5");
        zookeeper.start();
    }
}
